#include "Ball.h"
#include "Resource.h"
#include "Config.h"

Ball * Ball_Create(int x, int y, int rotateSpeed, double speedX, double speedY)
{
    Ball * b = malloc(sizeof(Ball));
    b->dest.x = x;
    b->dest.y = y;
    b->dest.w = 100;
    b->dest.h = 100;
    b->angle = 0;
    b->rotateSpeed = rotateSpeed;
    b->speedX = speedX;
    b->speedY = speedY;
    return b;
}

void Ball_Draw(Ball *self, SDL_Renderer *renderer)
{
    self->angle += self->rotateSpeed;
    self->dest.x += self->speedX;
    self->dest.y += self->speedY;

    /* 如果小球的x坐标大于X轴边界， 并且x轴速度大于0， 则反转x轴的速度*/
    if (((self->dest.x) > WINDOW_WIDTH - (self->dest.w))  && (self->speedX > 0)) {
        self->speedX *= -1;
    }

    /* 如果小球的X坐标小于0, 并且下轴速度是负的， 则反转X轴的速度*/
    if ((self->dest.x < 0) && (self-> speedX < 0)) {
        self->speedX *= -1;
    }

    /* 如果小球的x坐标大于Y轴边界， 并且Y轴速度大于0， 则反转Y轴的速度*/
    if (((self->dest.y) > WINDOW_HEIGHT - (self->dest.h))  && (self->speedY > 0)) {
        self->speedY *= -1;
    }

    /* 如果小球的Y坐标小于0, 并且Y轴速度是负的， 则反转Y轴的速度*/
    if ((self->dest.y < 0) && (self-> speedY < 0)) {
        self->speedY *= -1;
    }

    SDL_RenderCopyEx(renderer, Resource_GetBallTexture(),
                        NULL, &(self->dest), self->angle, NULL, SDL_FLIP_NONE);

    // int w, h;
    // SDL_QueryTexture(ball_Texture, NULL, NULL, &w, &h);
    // SDL_Rect srcRect = {0,0, w, h};
    // SDL_Rect desRect = {0,0, 300, 300};

    // static double angle = 0;
    // angle++;

    // for(int i=0; i<3; ++i) {
    //     SDL_Rect r2_destRect = {i*110, 0, 100, 100};
    //     SDL_RenderCopyEx(renderer, ball_Texture, NULL, &r2_destRect,
    //                         angle, NULL, SDL_FLIP_NONE);
    // }
}

void Ball_Destroy(Ball * ball)
{
    free(ball);
}